<template>
    <div class="login">
        <div class="clear inner_box">
            <div class="fl lf_cont"
                 v-loading="ctrLoading"
                 element-loading-text="拼命加载中"
                 element-loading-background="rgba(0, 0, 0, 0.8)">
                <div>
                    <img class="login-title" src="../assets/logo-yi.png">
                </div>
                <div class="top clear">
                    <a :class="['fl',{'active':Index===1}]"
                       @click="changeIndex(1)" href="javascript:;">扫码登陆</a>
                    <a :class="['fl',{'active':Index===2}]"
                       @click="changeIndex(2)" href="javascript:;">账号登录</a>
                </div>
                <div v-show="Index==2" class="default">
                    <div>
                        <el-form :model="loginForm"
                                 status-icon
                                 :rules="rules"
                                 ref="loginForm">
                            <el-form-item>
                                <el-input maxlength="11"
                                          v-model="loginForm.phone"
                                          placeholder="登录手机号/企业海关编码"></el-input>
                            </el-form-item>
                            <el-form-item prop="pass">
                                <el-input type="password"
                                          v-model="loginForm.pass"
                                          maxlength="24" placeholder="请输入密码"
                                          auto-complete="off"></el-input>
                            </el-form-item>
                            <el-row :gutter="20">
                                <el-col :span="14">
                                    <el-form-item prop="verifykey">
                                        <el-input
                                                v-model="loginForm.verifykey"
                                                @keyup.enter.native="submitForm('loginForm')"
                                                maxlength="4" placeholder="请输入图片数字"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <img
                                            :src="loginForm.imgcode"
                                            @click="getImgcode" id="codeimg" alt=""
                                            :style="{width:'84px',height:'40px'}"/>
                                </el-col>
                            </el-row>
                            <el-form-item>
                                <el-button
                                        @click="submitForm('loginForm')"
                                        :loading="loading"
                                        type="primary" style="width:100%">登录
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="somelink">
                        <a href="/company/password" class="getpassword">找回密码</a>
                        <a href="/company/register" class="register">注册激活</a>
                    </div>
                </div>
                <div v-show="Index==1" class="QR">
                    <div>
                        <img :src="qrUrl" alt="">
                        <a href="javascript:;">请打开手机扫一扫</a>
                    </div>
                </div>
            </div>

            <div class="fl img_bg">
                <img src="../assets/login-bg2.png" alt="">
            </div>
        </div>
         <p style="position: absolute;bottom: 20px;text-align: center;width: 100%;color:#070707;font-size: 14px;">技术支持：杭州佐梦软件技术有限公司</p>

    </div>
</template>

<script>
    import {
        fetchToken,
        fetchImgcode,
        getUserInfo,
        // isKey,
        QR,
        fetchHomeToken
    } from '@/api/login';
    import API from '@/utils/apiConfig'
    import {setToken} from '@/utils/auth';
    import {
        getOrderInfo3001L,
        getOrderInfo3002L,
        getOrderInfo3003L
    } from '@/api/order';

    export default {
        data() {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    callback();
                }
            };

            var vaildateNum = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请输入图片验证码'));
                } else {
                    var len = value.length;
                    if (len != 4) {
                        callback(new Error('请输入图片验证码'));
                    } else {
                        callback();
                    }
                }
            };
            return {
                qrUrl: '',
                Index: 1,
                ctrLoading: true,
                loginForm: {
                    phone: '',
                    pass: '',
                    imgcode: '',
                    verifykey: '',
                },
                rules: {
                    // phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
                    pass: [{required: true, validator: validatePass, trigger: 'blur'}],
                    verifykey: [{required: true, validator: vaildateNum, trigger: 'blur'}]
                },
                loading: false
            }
        },
        watch:{
            '$route'(to,from){

            }
        },
        created() {
            this.getHomeToken();
            this.initOrderData();

        },
        methods: {
            changeIndex(i) {
                this.Index = i;
            },
            submitForm(formName) {
                let that = this;
                that.$refs[formName].validate(valid => {
                    if (valid) {
                        that.loading = true;
                        fetchToken(
                            that.loginForm.phone,
                            that.loginForm.pass,
                            that.loginForm.verifykey,
                            'company'
                        )
                            .then(data => {
                                that.loading = true;
                                if (data.token) {
                                    setToken(data.token);
                                    localStorage.setItem('token',data.token)
                                    //获取用户数据
                                    getUserInfo()
                                        .then(data => {
                                            var myData = JSON.stringify(data.data); //转化为JSON字符串
                                            localStorage.setItem('UserInfo', myData);
                                            that.$router.push({path: '/'});
                                        })
                                        .catch(function (error) {
                                            console.log(error);
                                            that.loading = false;
                                            that.loginForm.pass = '';
                                            return;
                                        });
                                }
                            })
                            .catch(function (error) {
                                console.log(error);
                                that.loading = false;
                                that.loginForm.pass = '';
                                that.loginForm.verifykey = '';
                                that.getImgcode();
                            });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            initOrderData() {
                let that = this;
                //货源地
                getOrderInfo3001L('3008') //货源地
                    .then(data => {
                        var myData = data.data;
                        if (myData.length > 0) {
                            localStorage.setItem('30013008', JSON.stringify(data));
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

                getOrderInfo3001L('3003') //国别地区//已修改
                    .then(data => {
                        var myData = data.data;
                        if (myData.length > 0) {
                            //加入数据内容
                            localStorage.setItem('30013003', JSON.stringify(data));
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

                getOrderInfo3002L()
                    .then(data => {
                        var myData = data.data;
                        if (myData.length > 0) {
                            localStorage.setItem('3002', JSON.stringify(data));
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

                getOrderInfo3003L() //港口，已修改
                    .then(data => {
                        var myData = data.data;
                        if (myData.length > 0) {
                            localStorage.setItem('3003', JSON.stringify(data));
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

                getOrderInfo3001L('3010') //监管方式//已修改
                    .then(data => {
                        var myData = data.data;
                        if (myData.length > 0) {
                            localStorage.setItem('30013010', JSON.stringify(data));
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

                getOrderInfo3001L('3004') //已修改
                    .then(data => {
                        var myData = data.data;
                        if (myData.length > 0) {
                            localStorage.setItem('30013004', JSON.stringify(data));
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

                getOrderInfo3001L('3011') //已修改
                    .then(data => {
                        var myData = data.data;
                        if (myData.length > 0) {
                            localStorage.setItem('30013011', JSON.stringify(data));
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

                getOrderInfo3001L('3001') //修改过
                    .then(data => {
                        var myData = data.data;
                        if (myData.length > 0) {
                            localStorage.setItem('30013001', JSON.stringify(data));
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

                getOrderInfo3001L('3009') //已修改
                    .then(data => {
                        var myData = data.data;
                        if (myData.length > 0) {
                            localStorage.setItem('30013009', JSON.stringify(data));
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

                getOrderInfo3001L('3005') //已修改
                    .then(data => {
                        var myData = data.data;
                        if (myData.length > 0) {
                            localStorage.setItem('30013005', JSON.stringify(data));
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
                that.loading = false;
            },
            getImgcode() {
                let that = this;
                fetchImgcode()
                    .then(data => {
                        var n = data.data;
                        var src = 'data:image/jpg;base64,' + n;
                        that.loginForm.imgcode = src;
                    })
                    .catch(function (error) {
                        console.log(error);
                        that.loginForm.pass = '';
                        that.loginForm.verifykey = '';
                    });
            },
            getHomeToken() {
                let that = this;
                fetchHomeToken()
                    .then(data => {
                        if (data.token) {
                            //保存临时Token
                            localStorage.setItem('token', data.token);
                            this.getImgcode();
                            this.getQr();

                        } else {
                            new Error('获取用户识别码失败，请刷新页面后重新获取！');
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        that.loginForm.pass = '';
                        that.loginForm.verifykey = '';
                    });
            },
            getQr() {
                var that = this;
                let token = localStorage.getItem('token');
                let baseURL = API;
                var timer = null;
                clearInterval(timer)
                timer = setInterval(function () {
                    token = localStorage.getItem('token');
                    if(token){
                        that.qrUrl = `${baseURL}/weixin/1.0/company/qrcode/login?token=${token}`
                        setToken(token);
                        QR(token).then(res => {
                            that.ctrLoading = false;
                            if (res.code == 1) {
                                getUserInfo()
                                    .then(data => {
                                        var myData = JSON.stringify(data.data); //转化为JSON字符串
                                        localStorage.setItem('UserInfo', myData);
                                        that.$router.push({path: '/'});
                                    })
                                    .catch(function (error) {
                                        console.log(error);
                                        that.loading = false;
                                        that.loginForm.pass = '';
                                        return;
                                    });
                                clearInterval(timer)
                            }
                        }).catch(err => {
                            // clearInterval(timer)
                            console.log(err)
                        })
                    }

                }, 3000)

            }
        }

    }
</script>

<style scoped lang="scss">
    .QR {
        img {
            display: block;
            margin: 10px auto;
            height: 250px !important;
        }
        a {
            text-decoration: none;
            display: block;
            text-align: center;
            position: relative;
            top: -20px;
            color: #333;
        }
    }

    a {
        text-decoration: none;
    }

    .login {
        height: 100vh;
        width: 100vw;
        background: #0c75c1;
        -webkit-background-size: cover;
        background-size: cover;
        position: relative;
        overflow: hidden;
    }

    .fl {
        float: left;
    }

    .clear::after {
        display: block;
        content: '';
        clear: both;
    }

    .lf_cont, .img_bg {
        height: 420px;
        img {
            height: 420px;
            border: none;
        }
    }

    .lf_cont {
        width: 284px;
        background: #fff;
        .fl {
            width: 50%;
            text-align: center;
            line-height: 46px;
            text-decoration: none;
            border-bottom: 3px solid #ccc;
            color: #808080;
        }
        .active {
            border-bottom: 3px solid #0c75c1;
            color: #0c75c1;
        }
    }

    .inner_box {
        z-index: 9;
        position: absolute;
        left: 50%;
        margin-left: -328px;
        margin-top: -210px;
        top: 50%;
    }

    @import 'src/styles/mixin.scss';

    .somelink {
        margin: 0 20px;
        @include clearfix;
        a {
            display: block;
            color: #999;
            font-size: 14px;
        }
        .getpassword {
            float: left;
        }
        .register {
            float: right;
        }
    }

    .login-title {
        display: block;
        margin: 20px auto;
        height: 32px !important;
    }

    form {
        margin: 0 20px;
        margin-top: 20px;
    }

    .code_box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        input {
            margin: 0;
        }
    }

    .code {
        width: 80px;
        margin: 0;
    }
</style>
